<?php

namespace App\Console\Crons;

use App\Datalog\ErrorLog;
use App\Models\WxMiniprogramConfig;
use Illuminate\Support\Facades\Http;

class WxMiniprogramLimitCheckCron extends CronBase
{
    // 定时去检查未删除的小程序，他是否被腾讯封禁
    public function run($stime)
    {
        $list = WxMiniprogramConfig::where('is_limit', 0)->get();
        foreach ($list as $item) {
            $this->check($item);
        }
    }

    public function check(WxMiniprogramConfig $item)
    {
        $appid = $item->appid;
        $url = "https://mp.weixin.qq.com/mp/waerrpage?appid={$appid}&type=offshelf";
        $response = Http::get($url);
        if (!$response->ok()) {
            return false;
        }

        $body = $response->body();
        $body = str_replace(["\n", "\r", " "], '', $body);
        preg_match('/<h2class="weui-msg__title">(.*?)<\/h2>/', $body, $title);
        preg_match('/<pclass="weui-msg__desc">(.*?)<\/p>/', $body, $desc);

        $msg = $title[1] ?? '';
        if (strpos($msg, '违规') !== false || strpos($msg, '暂停') !== false) {
            $item->is_limit = 1;
            $item->limit_time = time();
            $item->save();

            ErrorLog::GetInstance()->addWxMiniprogramLimit($item, $msg);
        }
    }
}
